#include <QTimer>
#include <QFile>
#include <QDir>
#include <QTemporaryFile>

#include "mailcheckerthread.h"
#include "pop3invoker.h"
#include "emailmessage.h"

MailCheckerThread::MailCheckerThread(QString _playerEmail,QString _password,QString _pop3Server,
    QString _ownerEmail,QObject *parent)
    :QThread(parent),playerEmail(_playerEmail),password(_password),pop3Server(_pop3Server),ownerEmail(_ownerEmail),
      timer(NULL),enable(false)
{

}

MailCheckerThread::~MailCheckerThread()
{
}

void MailCheckerThread::SetPlayerEmailInfomation(QString _playerEmail,
    QString _password,QString _pop3Server,QString _ownerEmail)
{
    mailInfomationMutex.lock();
    playerEmail = _playerEmail;
    password = _password;
    pop3Server = _pop3Server;
    ownerEmail = _ownerEmail;
    mailInfomationMutex.unlock();
}

void MailCheckerThread::EnableCheckingThread(bool valid)
{
    switchMutex.lock();
    enable = valid;
    switchMutex.unlock();
}

void MailCheckerThread::run()
{
    QTimer threadTimer;
    timer = &threadTimer;
    timer->setInterval(60000);
    connect(timer,SIGNAL(timeout()),this,SLOT(CheckEmail()),Qt::DirectConnection);
    timer->start();
    exec();
}

void MailCheckerThread::CheckEmail()
{
    if(enable)
    {
        timer->stop();
        POP3Invoker mailReceiver;
        mailReceiver.Connect(pop3Server);
        mailReceiver.Login(playerEmail ,password);
        quint64 currentMailCount = 0;
        quint64 totalMailSize = 0;
        mailReceiver.Statistics(currentMailCount,totalMailSize);

        if(currentMailCount != 0)
        {
            QString currentUIDL;
            mailReceiver.GetUIDL(currentMailCount,currentUIDL);

            if(mailUniqueID != currentUIDL)
            {
                mailUniqueID = currentUIDL;
                QTemporaryFile mailTempFile;
                mailReceiver.Retrieve(&mailTempFile,currentMailCount);

                EmailMessage *mailParser = new EmailMessage();
                mailParser->open(&mailTempFile);

                if(mailParser->getFrom() == ownerEmail)
                {
                    QStringList attachList = mailParser->attachments();
                    QStringList attachPath;
                    for(QStringList::const_iterator iter = attachList.constBegin();
                        iter != attachList.constEnd(); ++iter)
                    {
                        QByteArray fileBuffer,contentType;
                        mailParser->readAttachment(*iter,fileBuffer,contentType);
                        qDebug(qPrintable(QDir::currentPath()));
                        QFile attachmentFile(QDir::current().filePath(*iter));
                        if(attachmentFile.open(QIODevice::WriteOnly))
                        {
                            attachmentFile.write(fileBuffer);
                            attachmentFile.close();
                        }
                        attachPath.append(QDir::current().filePath(*iter));
                    }
                    emit NewMediaFileReceived(attachPath);
                }
                else
                {
                    mailReceiver.TemporaryDelete(currentMailCount);
                }
                delete mailParser;
            }
        }
        mailReceiver.Quit();
        timer->start();
    }
}
